<script setup>
import { ref, reactive, onMounted } from "vue";
import orderApi from "@/api/orderApi";
import dayjs from "dayjs";
import { use } from "echarts/core";
import { PieChart, LineChart } from "echarts/charts";
import { ElAmap, ElAmapLayerHeatMap } from "@vuemap/vue-amap";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import VChart, { THEME_KEY } from "vue-echarts";
import Papa from 'papaparse';


use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  LineChart,
  CanvasRenderer,
  GridComponent
]);

const lineOption = reactive({
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(50,50,50,0.7)',
    borderColor: '#333',
    textStyle: {
      color: '#fff'
    },
    formatter: function (params) {
      const data = params[0];
      return `<strong>${data.name}</strong><br/>
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${data.color};"></span>
              订单量: <strong>${data.value}</strong>`;
    }
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#5470c6'
      },
      lineStyle: {
        width: 3
      },
      symbolSize: 8
    }
  ]
});

const nowLineOption = reactive({
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(50,50,50,0.7)',
    borderColor: '#333',
    textStyle: {
      color: '#fff'
    },
    formatter: function (params) {
      const data = params[0];
      return `<strong>${data.name}</strong><br/>
              <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${data.color};"></span>
              订单量: <strong>${data.value}</strong>`;
    }
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#91cc75'
      },
      lineStyle: {
        width: 3
      },
      symbolSize: 8
    }
  ]
});

const loading = ref(false);
const searchParam = reactive({
  addStartDate: dayjs().subtract(1, "M").format("YYYY-MM-DD"),
  addEndDate: dayjs().format("YYYY-MM-DD"),
});
const searchSaleDayParam = reactive({
  addStartDate: dayjs().format("YYYY-MM-DD"),
});
const searchSaleDateRangeParam = reactive({
  addStartDate: dayjs().subtract(1, "weeks").format("YYYY-MM-DD"),
  addEndDate: dayjs().format("YYYY-MM-DD"),
});
const scrollbar = ref(true);
const scroll = {
  x: 0,
  y: 400,
};

const hourGroupData = ref([]);
const hourSaleGroupData = ref([]);
const dateRangeSaleGroupData = ref([]);
const addTimeGroupData = ref([]);
const areaGroupData = ref([]);
const orderGoodCountData = ref([]);
const hourGroupColumns = [
  { title: "送货时间", dataIndex: "hour" },
  { title: "下单量", dataIndex: "total" },
];
const hourSaleGroupColumns = [
  { title: "下单时间", dataIndex: "title" },
  { title: "下单量", dataIndex: "total" },
  { title: "销售额", slotName: "totalSaleAmount" },
];

const dateRangeSaleGroupColumns = [
  { title: "下单日期", dataIndex: "title" },
  { title: "下单量", dataIndex: "total" },
  { title: "销售额", slotName: "totalSaleAmount" },
];

const addTimeGroupColumns = [
  { title: "下单时间", dataIndex: "hour" },
  { title: "下单量", dataIndex: "total" },
];

const areaGroupColumns = [
  { title: "区域", dataIndex: "area" },
  { title: "下单量", dataIndex: "total" },
];

const orderGoodGroupColumns = ref([
  { title: "产品名称", dataIndex: "产品名称", width: 200 },
  { title: "数量", dataIndex: "数量" },
  { title: "4英寸", dataIndex: "4英寸" },
  { title: "5英寸", dataIndex: "5英寸" },
  { title: "6英寸", dataIndex: "6英寸" },
  { title: "8英寸", dataIndex: "8英寸" },
  { title: "10英寸", dataIndex: "10英寸" },
]);


const goodAttrCountData = ref([]);
const lngLatData = ref([]);
const heatMapData = ref({
  data: [],
  max: 100
});
const zoom = ref(10);
const center = ref([118.797118, 32.05919]);
const mapVisible = ref(true);

const loadAnalysisData = () => {
  loading.value = true;
  orderApi.analysis(searchParam).then((res) => {
    generateHourGroupData(res.hourGroupSaleData);
    generateAddTimeGroupData(res.addTimeGroupSaleData);
    generateAreaGroupData(res.areaGroupSaleData);
    generateGoodGroupData(res.orderGoodCountData);

    if (res.lngLats && res.lngLats.length > 0) {
      console.log("原始热力图数据:", res.lngLats);

      const points = res.lngLats.map(item => ({
        lng: Number(item.lng),
        lat: Number(item.lat),
        count: item.count || 5
      }));

      heatMapData.value = {
        data: points,
        max: 50
      };

      console.log("处理后热力图数据:", JSON.stringify(heatMapData.value));


    } else {
      console.warn("未找到热力图数据");
    }

    loading.value = false;
  }).catch(err => {
    console.error("加载数据出错:", err);
    loading.value = false;
  });
};

const querySalesStatisticsByDateRange = () => {
  orderApi.salesStatisticsByDateRange(searchSaleDateRangeParam).then((res) => {
    dateRangeSaleGroupData.value = res;
  });
};

const querySalesStatisticsByDay = () => {
  orderApi.salesStatisticsByDay(searchSaleDayParam).then((res) => {
    hourSaleGroupData.value = res;
  });
};

const generateHourGroupData = (respData) => {
  let timeData = [];
  for (let p in respData) {
    timeData.push({
      hour: p,
      total: respData[p],
    });
  }
  timeData.sort((a, b) => a.hour.substring(0, 2) - b.hour.substring(0, 2));
  hourGroupData.value = timeData;
};

const generateAddTimeGroupData = (respData) => {
  let timeData = [];
  for (let p in respData) {
    timeData.push({
      hour: p,
      total: respData[p],
    });
  }
  timeData.sort((a, b) => a.hour.substring(0, 2) - b.hour.substring(0, 2));
  addTimeGroupData.value = timeData;
};

const generateAreaGroupData = (respData) => {
  let areaData = [];
  for (let p in respData) {
    areaData.push({
      area: p,
      total: respData[p],
    });
  }
  areaData.sort((a, b) => b.total - a.total);
  areaGroupData.value = areaData;
};

const generateGoodGroupData = (respData) => {
  let orderGoodData = [];
  for (let p in respData) {
    let countList = respData[p];
    let data = {
      '产品名称': p,
      '数量': 0,
      '4英寸': 0,
      '5英寸': 0,
      '6英寸': 0,
      '8英寸': 0,
      '10英寸': 0
    }
    countList.forEach(c => {
      data['数量'] = data['数量'] + c.count
      if (c.attrName == '4英寸') {
        data['4英寸'] = data['4英寸'] + c.count;
      }
      if (c.attrName == '5英寸') {
        data['5英寸'] = data['5英寸'] + c.count;
      }
      if (c.attrName == '6英寸') {
        data['6英寸'] = data['6英寸'] + c.count;
      }
      if (c.attrName == '8英寸') {
        data['8英寸'] = data['8英寸'] + c.count;
      }
      if (c.attrName == '10英寸') {
        data['10英寸'] = data['10英寸'] + c.count;
      }
    })
    orderGoodData.push(data);
  }
  orderGoodData.sort((a, b) => b['数量'] - a['数量']);
  orderGoodCountData.value = orderGoodData;
};

const summary = ({ columns, data }) => {
  let summaryData = {
    title: 0,
    total: 0,
    totalSaleAmount: 0,
  };
  data.forEach((record) => {
    summaryData.total += record.total;
    summaryData.totalSaleAmount += record.totalSaleAmount;
  });
  console.log(summaryData.totalSaleAmount);
  return [
    {
      title: "总计",
      total: summaryData.total,
      totalSaleAmount: summaryData.totalSaleAmount.toFixed(2)
    },
  ];
};

const exportCsv = () => {
  const csv = Papa.unparse(orderGoodCountData.value, {
    delimiter: ',',
    quotes: true,
    header: true
  });
  const blob = new Blob([csv], { type: 'text/csv' });

  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = 'summary.csv';
  link.click();
}


const summarySaleCount = ({ columns, data }) => {
  let summaryData = {
    title: 0,
    '数量': 0,
    '4英寸': 0,
    '5英寸': 0,
    '6英寸': 0,
    '8英寸': 0,
    '10英寸': 0
  };
  data.forEach((record) => {
    summaryData['数量'] += record['数量'];
    if (record['4英寸']) {
      summaryData['4英寸'] += record['4英寸'];
    }
    if (record['5英寸']) {
      summaryData['5v寸'] += record['5英寸'];
    }
    if (record['6英寸']) {
      summaryData['6英寸'] += record['6英寸'];
    }
    if (record['8英寸']) {
      summaryData['8英寸'] += record['8英寸'];
    }
    if (record['10英寸']) {
      summaryData['10英寸'] += record['10英寸'];
    }
  });

  return [
    {
      title: "总计",
      '数量': summaryData['数量'],
      '4英寸': summaryData['4英寸'],
      '5英寸': summaryData['5英寸'],
      '6英寸': summaryData['6英寸'],
      '8英寸': summaryData['8英寸'],
      '10英寸': summaryData['10英寸']
    },
  ];
};

const summaryForChart = (y) => {
  orderApi.summaryForChart({
    year: y
  }).then(res => {
    let xAxis = [];
    let seriesData = [];
    if (y == 'last') {
      res.forEach(item => {
        xAxis.push(item.mouth);
        seriesData.push(item['下单量']);
      })
      lineOption.xAxis.data = xAxis;
      lineOption.series[0].data = seriesData;

      // 设置图表标题
      lineOption.title = {
        text: '去年每月订单量统计',
        left: 'center'
      };
    } else {
      res.forEach(item => {
        xAxis.push(item.mouth);
        seriesData.push(item['下单量']);
      })
      nowLineOption.xAxis.data = xAxis;
      nowLineOption.series[0].data = seriesData;

      // 设置图表标题
      nowLineOption.title = {
        text: '今年每月订单量统计',
        left: 'center'
      };
    }
  })
}


querySalesStatisticsByDay();
querySalesStatisticsByDateRange();
loadAnalysisData();
summaryForChart('last');
summaryForChart('now');
</script>
<template>
  <div class="main-con">
    <a-card title="销售额统计" hoverable>
      <div style="padding: 16px 0">
        <a-grid :cols="{ xs: 1, sm: 2, md: 2, lg: 2, xl: 2, xxl: 2 }" :colGap="16" :rowGap="16">
          <a-grid-item>
            <a-card title="按下单日期（默认展示当天）" hoverable>
              <a-form :model="searchSaleDayParam" layout="inline" style="background-color: #fff">
                <a-form-item>
                  <a-date-picker v-model="searchSaleDayParam.addStartDate" format="YYYY-MM-DD"
                    placeholder="开始时间"></a-date-picker>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="querySalesStatisticsByDay">查询</a-button>
                </a-form-item>
              </a-form>
              <a-table :loading="loading" :scroll="scroll" :scrollbar="scrollbar" :sticky-header="20"
                :data="hourSaleGroupData" :columns="hourSaleGroupColumns" :pagination="false" :summary="summary"
                summary-text="合计">
                <template #totalSaleAmount="{ record }">
                  <span style="color: orange">¥{{ record.totalSaleAmount }}</span>
                </template>
              </a-table>
            </a-card>
          </a-grid-item>
          <a-grid-item>
            <a-card title="按下单时间范围（默认一周）" hoverable>
              <a-form :model="searchSaleDateRangeParam" layout="inline" style="background-color: #fff">
                <a-form-item>
                  <a-date-picker v-model="searchSaleDateRangeParam.addStartDate" format="YYYY-MM-DD"
                    placeholder="开始时间"></a-date-picker>
                </a-form-item>
                <a-form-item>
                  <a-date-picker v-model="searchSaleDateRangeParam.addEndDate" format="YYYY-MM-DD"
                    placeholder="结束时间"></a-date-picker>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="querySalesStatisticsByDateRange">查询</a-button>
                </a-form-item>
              </a-form>
              <a-table :loading="loading" :scroll="scroll" :scrollbar="scrollbar" :sticky-header="20"
                :data="dateRangeSaleGroupData" :columns="dateRangeSaleGroupColumns" :pagination="false"
                :summary="summary" summary-text="合计">
                <template #totalSaleAmount="{ record }">
                  <span style="color: orange">¥{{ record.totalSaleAmount }}</span>
                </template>
              </a-table>
            </a-card>
          </a-grid-item>
        </a-grid>
      </div>
    </a-card>
    <a-card title="下单量分组统计" hoverable style="margin-top: 16px">
      <div style="background-color: #f9f9f9; padding: 16px">
        <a-form :model="searchParam" layout="inline" style="background-color: #fff; padding: 16px">
          <a-form-item label="下单时间段（默认最近一个月）">
            <a-date-picker v-model="searchParam.addStartDate" format="YYYY-MM-DD" placeholder="开始时间"></a-date-picker>
          </a-form-item>
          <span>~</span>
          <a-form-item>
            <a-date-picker v-model="searchParam.addEndDate" format="YYYY-MM-DD" placeholder="结束时间"></a-date-picker>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="loadAnalysisData">查询</a-button>
          </a-form-item>
        </a-form>
        <div style="padding: 16px 0">
          <a-grid :cols="{ xs: 1, sm: 3, md: 3, lg: 3, xl: 3, xxl: 3 }" :colGap="16" :rowGap="16">
            <a-grid-item>
              <a-card title="按送货时间段" hoverable :bordered="false">
                <a-table :loading="loading" :scroll="scroll" :scrollbar="scrollbar" :sticky-header="20"
                  :data="hourGroupData" :columns="hourGroupColumns" :pagination="false"></a-table>
              </a-card>
            </a-grid-item>
            <a-grid-item>
              <a-card title="按区域" hoverable :bordered="false">
                <a-table :loading="loading" :scroll="scroll" :scrollbar="scrollbar" :sticky-header="20"
                  :data="areaGroupData" :columns="areaGroupColumns" :pagination="false"></a-table>
              </a-card>
            </a-grid-item>
            <a-grid-item>
              <a-card title="按下单时间段" hoverable :bordered="false">
                <a-table :loading="loading" :scroll="scroll" :scrollbar="scrollbar" :sticky-header="20"
                  :data="addTimeGroupData" :columns="addTimeGroupColumns" :pagination="false"></a-table>
              </a-card>
            </a-grid-item>
            <a-grid-item>
              <a-card title="去年每月统计" hoverable :bordered="false">
                <v-chart :option="lineOption" autoresize class="basechart"></v-chart>
              </a-card>
            </a-grid-item>
            <a-grid-item>
              <a-card title="今年每月统计" hoverable :bordered="false">
                <v-chart :option="nowLineOption" autoresize class="basechart"></v-chart>
              </a-card>
            </a-grid-item>
            <a-grid-item>
              <a-card title="订单区域热力图" hoverable :bordered="false">
                <div style="width: 100%; height: 430px; position: relative; border: 1px solid #eee;">
                  <ElAmap :zoom="zoom" :center="center"
                    style="width: 100%; height: 100%; position: absolute; top: 0; left: 0;" :resizeEnable="true">
                    <ElAmapLayerHeatMap :visible="true" :dataSet="heatMapData" :radius="30" :zIndex="10" :gradient="{
                      0.2: 'rgb(0, 0, 180)',
                      0.4: 'rgb(0, 0, 255)',
                      0.6: 'rgb(0, 255, 0)',
                      0.8: 'rgb(255, 255, 0)',
                      1.0: 'rgb(255, 0, 0)'
                    }" :opacity="[0.15, 1.0]" :zooms="[3, 20]">
                    </ElAmapLayerHeatMap>
                  </ElAmap>
                </div>
              </a-card>
            </a-grid-item>
          </a-grid>
        </div>
        <div style="padding: 16px 0">
          <a-card title="单品销量数据排名" hoverable :bordered="false">
            <template #extra>
              <a-button type="outline" @click="exportCsv">
                <template #icon>
                  <icon-download></icon-download>
                </template>
                导出
              </a-button>
            </template>
            <a-table :summary="summarySaleCount" summary-text="合计" :loading="loading" :scroll="scroll"
              :scrollbar="scrollbar" :sticky-header="20" :data="orderGoodCountData" :columns="orderGoodGroupColumns"
              :pagination="false"></a-table>
          </a-card>
        </div>
      </div>
    </a-card>
  </div>
</template>
<style lang="less" @scoped>
.basechart {
  height: 430px;
}

.map-loading {
  height: 430px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #666;
}
</style>